#ifdef _WIN32
	#include "ZiaServerWin/ZiaServerWin.h"
#else
	#include <unistd.h>
	#include "ZiaServerUnix/ZiaServerUnix.h"
#endif
#include <sstream>
#include <stdlib.h>
#include "Connection.hpp"


zia::Connection::Connection()
{
	mInfos = new zia::api::DataTree();
	setFdWriteCallback(sendCB);
	setFdReadCallback(recvCB);
}

zia::Connection::~Connection()
{
}


void				zia::Connection::close()
{
	std::string			sc;

	sc = ((*mInfos)["CliSock"]);
	std::cout << "CliSock = " << sc.c_str() << std::endl;
#ifdef _WIN32
	closesocket(atoi(sc.c_str()));
#else
	::close(atoi(sc.c_str()));
#endif
}

void				zia::Connection::setFdReadCallback(zia::api::FdCallback callback)
{
	callback = zia::api::FdCallback::create<zia::Connection, &zia::Connection::SendToCli>(this);
	return ;
}

void				zia::Connection::setFdWriteCallback(zia::api::FdCallback callback)
{
	callback = zia::api::FdCallback::create<zia::Connection, &zia::Connection::SendToCli>(this);
	this->sendCB = callback;
	return ;
}

void				zia::Connection::StockCliInfo(int sc, unsigned int ip)
{
	std::ostringstream	oss;
	std::ostringstream	osss;
	std::string			temp;

	oss << sc;
	temp = oss.str();
	(*mInfos)["CliSock"] = temp;
	osss << ip;
	temp = osss.str();
	(*mInfos)["IP"] = temp;
}

ssize_t	zia::Connection::SendToCli(zia::api::Resource, void *buf, size_t len)
{
	int	sc;
	std::string	str;

	str = ((*mInfos)["CliSock"]);
	sc = atoi(str.c_str());
	send(sc, (char *)buf, len, 0);
	return (0);
}

ssize_t	zia::Connection::RecvFromCli(zia::api::Resource, void *buf, size_t len)
{
	int	sc;
	std::string	str;

	str = ((*mInfos)["CliSock"]);
	sc = atoi(str.c_str());
	recv(sc, (char *)buf, len, 0);
	return (0);
}

zia::api::FdCallback	zia::Connection::getSendCB()
{
	return (this->sendCB);
}
